<template>
    <panel-layout :title="`${formData.id ? '编辑' : '添加'}用户`">
        <el-form
            class="form"
            ref="form"
            label-width="110px"
            :model="formData"
            :rules="rules"
        >
            <el-form-item
                label="姓名"
                prop="name"
            >
                <el-input
                    v-model="formData.name"
                    placeholder="请输入姓名"
                ></el-input>
            </el-form-item>

            <el-form-item
                label="联系电话"
                prop="phone"
            >
                <el-input
                    v-model="formData.phone"
                    placeholder="请输入手机号码"
                ></el-input>
            </el-form-item>

            <el-form-item
                label="密码"
                prop="passwd"
            >
                <el-input
                    v-model="formData.passwd"
                    placeholder=""
                ></el-input>
            </el-form-item>

            <el-form-item
                label="用户类型"
                prop="type"
            >
                <template>
                  <el-select v-model="formData.type" placeholder="请选择">
                    <el-option
                      v-for="item in typeOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value">
                    </el-option>
                  </el-select>
                </template>
            </el-form-item>

            <el-form-item
                label="状态"
                prop="status"
            >
                <el-switch
                  v-model="formData.status"
                  :active-value="1"
                  :inactive-value="0">
                </el-switch>
            </el-form-item>

            <el-form-item
                label="权限组"
                prop="roleList"
            >
                <el-divider></el-divider>

                <template>
                  <el-checkbox-group v-model="formData.roleList" @change="handleCheckedRoleChange">
                    <el-checkbox v-for="role in roleOptions" :label="role.id" :key="role.id">{{role.name}}</el-checkbox>
                  </el-checkbox-group>
                </template>
            </el-form-item>

            <div class="form-btns">
                <div class="btn">
                    <el-button @click="cancel">取消</el-button>
                </div>
                <div class="btn">
                    <el-button
                        type="primary"
                        v-permission="['member-save']"
                        @click="save"
                    >保存</el-button>
                </div>
            </div>
        </el-form>
    </panel-layout>
</template>

<script>
import { getUserDetail, newUser, updateUser } from '@/api/user'
import { getRoleList } from '@/api/role'
import permission from "@/directive/permission/index.js"
import editFormPanel from '@/mixins/editFormPanel'
export default {
	name: 'UserDetail',
	mixins: [editFormPanel],
    directives: { permission },
	props: {
		id: {
			type: [String, Number],
			default() {
				return ''
			}
		}
	},
	data() {
		return {
			formData: {
				name: '',
				phone: '',
                oldPasswd: '',
				passwd: '',
                type: 0,
                status: 1,
                avatar: '',
                roleList: []
			},
			rules: {
				name: [
					{ required: true, message: '请输入姓名', trigger: 'blur' },
					{ max: 10, message: '姓名不能超过10个字符', trigger: 'change' }
				],
				phone: {
					required: true,
					validator: (rule, val, callback) => {
						let reg = /^800[0-9]{7}|^400[0-9]{7}|(^0\d{2,3}-\d{7,8}$)|(^[1][3,4,5,6,7,8,9][0-9]\d{8}$)/
						if (!reg.test(val)) {
							callback(new Error('请输入正确的电话号码'))
						}
						callback()
					},
					trigger: 'blur'
				}
			},
            typeOptions: [{"value": 0, "label": "用户"}, {"value": 999, "label": "开发者"}],
            roleOptions: []
		}
	},
	created() {
		this.getRoles()

        if (this.id !== '') {
			this.formData.id = this.id
			this.getPageDetail()
		}
	},
	methods: {
		getPageDetail() {
			getUserDetail({ id: this.formData.id }).then((res) => {
				for (let key in this.formData) {
					if (key == 'passwd') {
                        this.formData['oldPasswd'] = res.data[key]
                    } else if (key == 'roleList') {
                        this.formData[key] = res.data[key] || []
                    } else {
                        this.formData[key] = res.data[key]
                    }
				}
				this.$nextTick(() => {
					this.$emit('getIsChangeFormData', false)
				})
			})
		},
        getRoles() {
        	getRoleList({}).then((res) => {
        		this.roleOptions = res.data
        	})
        },
		cancel() {
			this.$emit('closeDrawer')
		},
		save() {
			this.$refs.form.validate((valid) => {
				if (valid) {
					let params = this.formData
					// Object.keys(this.formData).forEach((key) =>
					// 	this.formData[key] ? (params[key] = this.formData[key]) : ''
					// );
                    
                    // if (this.formData['passwd'] == '') {
                    //     params['passwd'] = this.formData['oldPasswd']
                    // }
                    
                    // console.log('formData', this.formData)
                    // console.log('params', params)
					// 根据id是否存在判断是新增还是修改
					;(() => [newUser, updateUser][!params.id ? 0 : 1](params))().then((res) => {
						if (res.err_code === 0) {
							this.$message.success(res.err_msg || 'success')
							this.$emit('getIsChangeFormData', false)
							this.$emit('getPageData')
							this.$emit('closeDrawer')
						}
					})
				}
			})
		},
        handleCheckedRoleChange() {
            console.log(this.formData.roleList)
        }
	}
}
</script>

<style lang="scss" scoped>
    .el-checkbox {
        width: 25%;

        .el-checkbox__label{
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }
    }
</style>
